package com.guosheng.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JsonUtil {

    /**
     * 使用正则表达式，将json字符串中的所有数组置为null
     */
    public static String jsonUpdateArrayToNull(String json){
        Pattern pattern = Pattern.compile("\\[(.*?)\\]");
        Matcher matcher = pattern.matcher(json);
        StringBuilder sb = new StringBuilder(json);
        while(matcher.find()){
            String tmp = matcher.group(1);
            int start = matcher.start();
            sb.replace(start,start+tmp.length()+2,"null");
            json = sb.toString();
            matcher = pattern.matcher(json);
        }
        return json;
    }

    /**
     * return 0:既不是array也不是object
     * return 1：是object
     * return 2 ：是Array
     */
    public static int testIsObject1(String jsonString){
        try {
            JSONObject object = JSON.parseObject(jsonString);
            return 1;
        } catch (Exception e) {// 抛错 说明JSON字符不是数组或根本就不是JSON
            try {
                JSONArray array = JSON.parseArray(jsonString);
                return 2;
            } catch (Exception ee) {// 抛错 说明JSON字符根本就不是JSON
                return 0;
            }
        }
    }

    /**
     * 删除json字符串中的数组
     * @param json
     * @return
     */
    public static String jsonDelArray(String json){
        JSONObject obj = JSON.parseObject(json);
        Map<String,Object> map = new HashMap<>();
        for(Object k : obj.keySet()){
            Object v = obj.get(k);
            if(v instanceof JSONArray){
                continue;
            }
            map.put(k.toString(),v);
        }
        return JSON.toJSONString(map);
    }
}
